package 练习05_用线程池改造异步查询订单和收货地址;

import java.util.concurrent.*;

/**
 * @ClassName: TestThreadSearch
 * @Author: AllenSun
 * @Date: 2022/3/21 下午10:57
 */
public class TestThreadPoolSearch3 {

    public static String getOrder() {
        try {
            Thread.sleep(10);
            System.out.println("获取订单信息");
            ctl.countDown();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return "订单信息";
    }

    public static String getAddress() {
        try {
            Thread.sleep(1000);
            System.out.println("获取地址信息");
            ctl.countDown();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return "地址信息";
    }

    private static final CountDownLatch ctl = new CountDownLatch(2);

    public static void main(String[] args) throws ExecutionException, InterruptedException {

        ThreadPoolExecutor executor= new ThreadPoolExecutor(
                5,
                10,
                15,
                TimeUnit.SECONDS,
                new LinkedBlockingQueue<Runnable>()
        );

        long start = System.currentTimeMillis();
        //异步执行
        //使用executorService提交异步线程任务，future整合结果
        Future<String> futureOrder = executor.submit(new Callable<String>() {
            @Override
            public String call() throws Exception {
                String result = getOrder();
                return result;
            }
        });
        // Future<?> futureOrder = executor.submit(() -> {
        //     getOrder();
        // });
        // Future的get方法会阻塞线程直到任务完成，所以最后的耗时还是2秒多
        String orderInfo = futureOrder.get();
        System.out.println(orderInfo);

        Future<String> futureAddress = executor.submit(new Callable<String>() {
            @Override
            public String call() throws Exception {
                String result = getOrder();
                return result;
            }
        });
        // Future<?> futureAddress = executor.submit(() -> {
        //     getAddress();
        // });
        String addressInfo = futureAddress.get();
        System.out.println(addressInfo);

        //等待完成
        ctl.await(2000, TimeUnit.SECONDS);//最多等待20秒，不管子线程完没完

        long end = System.currentTimeMillis();

        //花费时间：1053
        System.out.println("花费时间："+(end-start));

        executor.shutdown();

    }
}
